package com.globaldom.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.globaldom.model.Gift;
import com.globaldom.utils.EMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/getallallies")
public class AlliesGetAllController {
	public AlliesGetAllController() {
	}

	private static final Logger log = Logger.getLogger(AlliesGetAllController.class.getName());

	@SuppressWarnings({"deprecation"})
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(HttpServletRequest request, Model model, HttpSession session) {
		
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			return "loggedout";
			}
		// List<Allies> allies;
		EntityManager em = EMF.get().createEntityManager();
		try {
			// String sql = "Select a from Allies a where personID=:pid";
			// Query q = em.createQuery(sql);
			// q.setParameter("pid", personID);
			// allies = q.getResultList();
			// if (null == allies || allies.size() < 1) {
			// allies = new ArrayList<Allies>();
			// for (int z = 1000; z < 1025; z++) {
			// Allies ally = new Allies();
			// ally.setAllyID((long) z);
			// ally.setAllyType(1);
			// allies.add(ally);
			// }
			// }
			// model.addAttribute("allies", allies);

			Date d = new Date();
			d.setHours(0);
			d.setMinutes(0);
			d.setSeconds(0);
			String sql = "Select g from Gift g where giftType=0 and giftSender=:personid and createDate>:todaydate";
			Query q = em.createQuery(sql);
			q.setParameter("todaydate", d);
			q.setParameter("personid", personID);
			List<Gift> gifts = q.getResultList();
			model.addAttribute("gifts", new ArrayList(gifts));
			model.addAttribute("moi", personID);
			sql = "Select g from Gift g where giftReceiver=:personid";
			q = em.createQuery(sql);
			q.setParameter("personid", personID);
			List<Gift> mygifts = q.getResultList();
			model.addAttribute("mygifts", new ArrayList(mygifts));

		} catch (Exception ex) {
			log.severe("Unable to get all allies " + ex.getLocalizedMessage());
			ex.printStackTrace();
		} finally {
			em.close();
		}
		return "allies";
	}
}
